import {Component, OnInit, Inject, ElementRef} from '@angular/core';
import { FormControl, FormGroup} from '@angular/forms';
import { PeopleService} from '../service/people.service';
import {People} from '../people';
import { Routes} from '@angular/router';
import { Router} from '@angular/router';
import {AppRoutingModule} from '../app-routing.module';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  url: string;
  tip: string;
  people: People[];
  loginForm = new FormGroup({
    username: new FormControl(''),
    password: new FormControl(''),
});

toRegister() {
  this.router.navigate(['login/register']);
}

  onSubmit() {
    this.loginWithCredentials(this.loginForm.value.username, this.loginForm.value.password);
  }

  loginWithCredentials(username: string, password: string): Promise<People> {
    return this.peopleService.getPeopleByPid(username)
      .then(people => {
        const that = this;
        const auth = new People();
        if (username.length === 0 || password.length === 0) {
          this.tip = '证件号或密码不能为空';
          setTimeout(function () {
            that.tip = null;
          }, 1000);
        } else if (username.length !== 0 && people.valueOf().toString() === '') {
          this.tip = '该用户不存在';
          setTimeout(function () {
            that.tip = null;
          }, 1000);
        } else if (password === people[0].password) {
          if (people[0].position === 0) {
            this.url = 'master';
            this.router.navigate(['login/master']);
          } else {
            this.url = 'reader';
            this.router.navigate(['login/reader']);
          }
          sessionStorage.setItem('usr', JSON.stringify(people[0]));
        } else {
          this.tip = '密码错误';
          setTimeout(function () {
            that.tip = null;
          }, 1000);
        }
        return auth;
      })
      .catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
  constructor(private peopleService: PeopleService, private router: Router) { }

  ngOnInit() {
    this.peopleService.getPeople().then(people => this.people = people);
  }

}
